package com.grj.template.boot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.grj.template.boot.domain.*;
import com.grj.template.boot.service.PermissionService;
import com.grj.template.boot.service.RolePermissionService;
import com.grj.template.boot.service.UserRoleService;
import com.grj.template.boot.service.UserService;
import com.grj.template.boot.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("login")
@Api(tags = "登录管理")
@RequiredArgsConstructor
public class LoginController {

    private final AuthenticationManager authenticationManager;

    private final UserDetailsService userDetailsService;

    private final JwtUtil jwtUtil;

    private final UserService userService;

    private final UserRoleService userRoleService;
    private final RolePermissionService rolePermissionService;
    private final PermissionService permissionService;

    @PostMapping
    @ApiOperation(value = "用户登录", notes = "根据User对象创建新用户")
    public R<LoginResponse> createAuthenticationToken(@RequestBody User user) throws Exception {
        try{
            authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()));
        }catch (Exception e){
            throw new Exception("用户名不存在或密码错误:"+this.getClass().getName());
        }
        final UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUsername());
        User loginUser = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
        final String jwt = jwtUtil.generateToken(userDetails.getUsername(), loginUser.getUserId());
        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setToken(jwt);
        loginResponse.setUser(loginUser);


        List<UserRole> userRoles = userRoleService.list(Wrappers.lambdaQuery(UserRole.class).eq(UserRole::getUserId, loginUser.getUserId()));
        List<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        List<Long> permissionIds = rolePermissionService.list(Wrappers.lambdaQuery(RolePermission.class).in(RolePermission::getRoleId, roleIds)).stream().map(RolePermission::getPermissionId).collect(Collectors.toList());
        List<Permission> permissionList =  permissionService.fetchPermissionMenuByIds(permissionIds);
        loginResponse.setPermissionList(permissionList);
        return R.ok("登录成功", loginResponse);
    }

}
